<template>
  <div class="auth-page">
    <div class="auth-container">
      <h2 class="title">用户注册</h2>

      <form @submit.prevent="handleSubmit" class="auth-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="form.username"
            type="text"
            placeholder="请输入用户名"
            required
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            required
          />
        </div>

        <div class="form-group">
          <label for="phone">手机号</label>
          <input id="phone" v-model="form.phone" type="tel" placeholder="请输入手机号" required />
        </div>

        <div class="form-group">
          <label for="email">邮箱 <span class="optional">(可选)</span></label>
          <input id="email" v-model="form.email" type="email" placeholder="请输入邮箱" />
        </div>

        <div class="form-group">
          <label>性别</label>
          <div class="radio-group">
            <label> <input type="radio" v-model.number="form.gender" :value="0" /> 未知 </label>
            <label> <input type="radio" v-model.number="form.gender" :value="1" /> 男 </label>
            <label> <input type="radio" v-model.number="form.gender" :value="2" /> 女 </label>
          </div>
        </div>

        <div class="form-actions">
          <button type="submit" class="submit-btn" :disabled="loading">
            {{ loading ? '注册中...' : '注册' }}
          </button>
          <div v-if="errorMessage" class="error-message">
            {{ errorMessage }}
          </div>
          <div v-if="successMessage" class="success-message">
            {{ successMessage }}
          </div>
          <router-link to="/login" class="switch-link">已有账号？立即登录</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '@/api/auth'

interface RegisterForm {
  username: string
  password: string
  phone: string
  email?: string
  gender?: 0 | 1 | 2
}

const router = useRouter()
const form = reactive<RegisterForm>({
  username: '',
  password: '',
  phone: '',
  email: '',
  gender: 0,
})

// 确保每次进入页面都清空表单
onMounted(() => {
  form.username = ''
  form.password = ''
  form.phone = ''
  form.email = ''
  form.gender = 0
  errorMessage.value = ''
  successMessage.value = ''

  // 清除可能的自动填充
  const inputs = document.querySelectorAll('input')
  inputs.forEach((input) => {
    input.value = ''
    input.autocomplete = 'off'
  })
})
const loading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

const validateMobile = (mobile: string): boolean => {
  return /^1[3-9]\d{9}$/.test(mobile)
}

const validateEmail = (email: string): boolean => {
  return email === '' || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}

const handleSubmit = async () => {
  // 重置消息
  errorMessage.value = ''
  successMessage.value = ''

  // 前端验证
  if (!form.username.trim()) {
    errorMessage.value = '请输入用户名'
    return
  }

  if (!form.password) {
    errorMessage.value = '请输入密码'
    return
  }

  if (!form.phone) {
    errorMessage.value = '请输入手机号'
    return
  }

  if (!validateMobile(form.phone)) {
    errorMessage.value = '请输入有效的11位手机号'
    return
  }

  if (form.email && !validateEmail(form.email)) {
    errorMessage.value = '请输入有效的邮箱格式'
    return
  }

  try {
    loading.value = true

    const response = await register({
      username: form.username.trim(),
      mobile: form.phone,
      password: form.password,
      ...(form.email ? { email: form.email.trim() } : {}),
      gender: form.gender ?? 0,
    })

    // 统一响应处理逻辑
    console.group('注册响应详情')
    console.log('完整响应对象:', response)
    console.groupEnd()

    // 处理可能的嵌套结构
    const responseData = response?.data || response
    const user = responseData?.user || {}
    const accessToken = responseData?.access || responseData?.access_token
    const refreshToken = responseData?.refresh || responseData?.refresh_token

    if (accessToken && refreshToken) {
      // 存储token
      localStorage.setItem('access_token', accessToken)
      localStorage.setItem('refresh_token', refreshToken)

      // 存储用户信息（如果有）
      if (Object.keys(user).length > 0) {
        localStorage.setItem('user', JSON.stringify(user))
      }

      successMessage.value = '注册成功！即将跳转到首页...'
      await nextTick()
      await new Promise((resolve) => setTimeout(resolve, 1000))
      router.push('/')
    } else {
      console.error('无法处理的响应结构:', response)
      errorMessage.value =
        responseData?.message || responseData?.detail || '注册过程中发生错误，请稍后重试'
    }
  } catch (error: any) {
    console.error('注册错误:', error)

    // 更健壮的错误处理
    if (error.response) {
      // 请求已发出且服务器响应了状态码，但状态码不在2xx范围内
      errorMessage.value =
        error.response.data?.message ||
        error.response.data?.detail ||
        error.response.statusText ||
        '注册失败，服务器返回错误'
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage.value = '网络错误，请检查您的连接'
    } else {
      // 其他错误
      errorMessage.value = error.message || '注册过程中发生未知错误'
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.auth-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;

  .auth-container {
    width: 400px;
    padding: 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .title {
      text-align: center;
      margin-bottom: 30px;
      color: #333;
      font-size: 24px;
    }

    .auth-form {
      .form-group {
        margin-bottom: 20px;

        label {
          display: block;
          margin-bottom: 8px;
          font-size: 14px;
          color: #666;
        }

        input {
          width: 100%;
          padding: 12px;
          border: 1px solid #ddd;
          border-radius: 4px;
          font-size: 14px;

          &:focus {
            border-color: #f56c6c;
            outline: none;
          }
        }

        .optional {
          color: #999;
          font-size: 12px;
        }

        .radio-group {
          display: flex;
          gap: 20px;
          margin-top: 8px;

          label {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
          }
        }
      }

      .form-actions {
        display: flex;
        flex-direction: column;
        gap: 15px;

        .submit-btn {
          background: linear-gradient(to right, #ff4e50, #f9d423);
          color: white;
          border: none;
          padding: 12px;
          border-radius: 4px;
          font-size: 16px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            opacity: 0.9;
          }

          &:disabled {
            background: #ccc;
            cursor: not-allowed;
          }
        }

        .error-message {
          color: #f56c6c;
          font-size: 14px;
          text-align: center;
          margin-top: 10px;
        }

        .success-message {
          color: #67c23a;
          font-size: 14px;
          text-align: center;
          margin-top: 10px;
        }

        .switch-link {
          text-align: center;
          color: #f56c6c;
          font-size: 14px;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }
}
</style>
